package com.example.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.common.Constants;
import com.example.dto.LoginUserDTO;
import com.example.entity.Menu;
import com.example.entity.Role;
import com.example.entity.User;
import com.example.exception.ServiceException;
import com.example.mapper.MenuMapper;
import com.example.mapper.RoleMapper;
import com.example.mapper.RoleMenuMapper;
import com.example.service.UserService;
import com.example.mapper.UserMapper;
import com.example.util.JwtUtil;
import com.example.vo.UserVo;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
* @author Administrator
* @description 针对表【user(用户表)】的数据库操作Service实现
* @createDate 2025-07-04 09:23:01
*/
@Service
@Transactional(rollbackFor = Exception.class)
@RequiredArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService{

    private final RoleMapper roleMapper;
    private final RoleMenuMapper roleMenuMapper;
    private final MenuMapper menuMapper;

    @Override
    public void register(User user) {
        /**
         * 判断用户名是否已存在
         */
        User u = this.getOne(Wrappers.<User>lambdaQuery().eq(User::getUserName, user.getUserName()));
        if (u!=null){
            throw new ServiceException("用户已存在");
        }

        /**
         * 保存用户
         */
        user.setRole(Constants.ROLE_USER); // 默认用户角色为普通用户
        save(user);
    }

    @Override
    public UserVo login(LoginUserDTO loginUserDTO) {
        /**
         * 先判断用户名密码是否正确
         */
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUserName, loginUserDTO.getUserName());
        wrapper.eq(User::getPassword, loginUserDTO.getPassword());
        User user = getOne(wrapper);
        if (user == null){
            throw new ServiceException("用户名或密码错误");
        }

        /**
         * 封装数据
         */
        UserVo userVo = new UserVo();
        BeanUtils.copyProperties(user, userVo);

        // 生成token
        Map<String, Object> payload = new HashMap<>();
        payload.put("id", user.getId());
        payload.put("userName", user.getUserName());
        String token = JwtUtil.generate(payload);
        userVo.setToken(token);

        // 获取用户的菜单列表
        String roleFlag = user.getRole();
        List<Menu> menus = menuMapper.selectByRoleFlag(roleFlag);

        // 获取一级菜单
        List<Menu> list = menus.stream()
                .filter(item -> item.getPid() == null)
                .map(item -> {
                    // 获取二级菜单
                    List<Menu> children = menus.stream()
                            .filter(subItem -> item.getId().equals(subItem.getPid())) // 这里要使用equals，不能使用==
                            .collect(Collectors.toList());
                    item.setChildren(children);
                    return item;
                })
                .collect(Collectors.toList());

        userVo.setMenus(list);
        return userVo;
    }

}




